Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

202
Vistas
React Hook "React.useState" cannot be called inside a callback. React Hooks must be called in a React function component

I am trying to make a default state based on user context but I couldn't get to use context outside tha callback of <myContext.Consumer>{myContext => {}}</myContext.Consumer>. I get the above error when I try to use setState in the callback

Here is my use case:

import * as React from 'react'
import Box from '@mui/material/Box'
import PageTitle from '../01_shared/PageTitle'

import { appCtx } from '../01_shared/appContext'

const MyComponent = () => {

  const [options, setOptions] = React.useState({
    currency: userContext.currency, // <=I need user context information here
  })

  return <appCtx.Consumer>{translationContext => {
    // I cannot use React.useState here
    return (
      <Box>
        <PageTitle>Hello {userCtx.firstName} you have 3 {options.currency}</PageTitle>
      </Box>
    )
  }}</appCtx.Consumer>
};

export default MyComponent

I know I can set the state straight after having access to the userContext but that seem more like a workaround than a proper solution.

Could you point me to the right direction please ?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Function components can use the useContext hook to get context values, and thus you don't need to render an <appCtx.Consumer>:

const MyComponent = () => {
  const userContext = React.useContext(appCtx);
  const [options, setOptions] = React.useState({
    currency: userContext.currency,
  });

  return (
    <Box>
      <PageTitle>
        Hello {userContext.firstName} you have 3 {options.currency}
      </PageTitle>
    </Box>
  );
};
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda